<template>
  <div class="content">
    <div class="headTop">
      <div style="color: rgb(136, 136, 136);text-align: center;">{{plan.hallName}}</div>
      <div class="statusList">
        <div class="topList">
          <div class="typeIcon2" style="border: 1px solid #33333350;border-radius: 3px;"></div><div class="typeName">不可售</div>
          <div class="typeIcon"></div><div class="typeName">已售</div>
          <div v-if="areas.length==0" class="typeIcon2" style="border: 1px solid rgb(180, 223, 247);border-radius: 3px;"></div><div class="typeName" v-if="areas.length==0">{{plan.price}}</div>
          <div v-for="(item,index) in areas" :key="index" style="display: flex;align-items: center;">
            <div class="typeIcon2" :style="{'border': item.color}" style="border-radius: 3px;"></div>
            <div class="typeName">{{item.price}}</div>
          </div>
          <!-- 是否有情侣座 -->
          <div v-if="isLove" style="display: flex;align-items: center;">
            <div class="lovers"></div>
            <div class="typeName">情侣座</div>
          </div>
         </div>
      </div>
    </div>

    <div style="height: 80px;"></div>

    <div class="rowContent">
      <div class="leftNumber" :style="{'height':maxHeight()}">
        <div v-for="(item,index) in list" :key="index" class="leftList">
          {{item[0]?item[0].seatRow:'-'}}
        </div>
      </div>
      <div style="margin-left: 10px;width: 330px;overflow: hidden;overflow-x: scroll;position: relative;" :style="{'height':maxHeight()}">
        <div class="wSild" :style="{'width':maxWidth(),'top':sildTop()}"></div>
        <div class="hSild" :style="{'height':maxHeight(),'left':sildLeft()}"></div>
        <div class="rowList" v-for="(item,index) in list" :key="index" :style="{'width':maxWidth()}">
            <div v-for="(it,idx) in item" :key="idx">
              <div v-if="it.seatState==-1">
                <div v-if="it.seatType!='R'&&it.seatType!='L'" @click="bindClick(it,index,idx)" class="colList5"
                :style="{'marginLeft':currentLeft(it.graphCol,idx==0?0:item[Number(idx-1)].graphCol,idx,idx==0?it.seatType:item[Number(idx-1)].seatType)}"></div>
                <div v-if="it.seatType=='L'" @click="bindClick(it,index,idx)" class="colList6"
                :style="{'marginLeft':currentLeft(it.graphCol,idx==0?0:item[Number(idx-1)].graphCol,idx,idx==0?it.seatType:item[Number(idx-2)].seatType)}"></div>
              </div>
              <div v-else>
                <div v-if="it.seatType!='R'&&it.seatType!='L'" @click="bindClick(it,index,idx)" :class="it.isFlase?'colList2':'colList'"
                :style="{'marginLeft':currentLeft(it.graphCol,idx==0?0:item[Number(idx-1)].graphCol,idx,idx==0?it.seatType:item[Number(idx-1)].seatType),'border':it.isFlase?it.color:'none'}"></div>
                <div v-if="it.seatType=='L'" @click="bindClick(it,index,idx)" :class="it.isFlase?'colList3':'colList4'"
                :style="{'marginLeft':currentLeft(it.graphCol,idx==0?0:item[Number(idx-1)].graphCol,idx,idx==0?it.seatType:item[Number(idx-2)].seatType)}"></div>
              </div>
            </div>
          </div>
        </div>
      </div>

    <div class="bottom">
      <div class="detail">
        <div class="detailTitle">
          <div class="name">{{plan.filmName}}</div>
          <!-- <div class="select"></div> -->
        </div>
        <div class="times">
          {{plan.stime}} {{plan.copyLanguage}}{{plan.copyType}}
        </div>
      </div>
      <div class="selectAdd" v-if="selectList.length>0">
        <div class="fengexian"></div>
        <div class="addList">
          <div class="listDetail" v-for="(item,index) in selectList" :key="index">
            <div class="listLeft">
              <div class="number">{{(item.seatRow)+'排'+(item.seatCol)+'坐'}}</div>
              <div class="price">￥{{item.price}}</div>
            </div>
            <div class="close" @click="bindClick(item)"></div>
          </div>
        </div>
      </div>
      <div class="button" v-if="selectList.length==0">请先选座</div>
      <div class="button2" v-else @click="gotoOrder">￥{{allPrice}} 确认选座</div>
    </div>

  </div>
</template>

<script>
import {
  setStore,
  getStore,
  removeStore
} from '@/utils/storage'
import wx from 'weixin-js-sdk'
const Big = require('big.js')
import {Dialog} from 'vant';
import {getPlanSeat,userInfo,order,prepay} from '@/api/home.js'
export default {
  name: "clientPresent",
  data() {
    return {
      list:[],
      selectList:[],
      cinemaId:'',
      featureAppNo:'',
      areas:[],
      plan:{},
      isLove:false,
      maxLength:0,
      allPrice:0,
      endHeight:''
    };
  },
  computed: {
    // 判断每个座位距离
      currentLeft() {
        return function(graphCol,oldgraphCol,type,oldtype){
          // console.log(graphCol,oldgraphCol,type,oldtype)
          let number = ''
          if(oldtype=='N'){
            number = (graphCol-oldgraphCol)==1?1.5:(graphCol-oldgraphCol-1)*4+1.5

          }
          if(oldtype=='L'){
            number = (graphCol-oldgraphCol)==1?1.5:(graphCol-oldgraphCol-1)*5+1.5
          }
          return number+'vh'
        }
      },
  },
  mounted() {
    this.featureAppNo = this.$route.query.featureAppNo
    this.cinemaId = this.$route.query.cinemaId
    this.userInfo()


  },
  methods: {
    // 判断最长宽度
    maxWidth(){
      let arr = []
      this.list.forEach((item,index)=>{
        arr.push(item.length)
      })
      arr.sort(function(a,b){
        return b - a
      })
      return Number(arr[0]*3.75) + 'vh'
    },
    //获取高度
    maxHeight(){
      return (this.endHeight*3.75+1.25)+'vh'
    },
    //定位高度
    sildTop(){
      return (this.endHeight*3.75+1.25)/2+'vh'
    },
    //定位宽
    sildLeft(){
      let arr = []
      this.list.forEach((item,index)=>{
        arr.push(item.length)
      })
      arr.sort(function(a,b){
        return b - a
      })
      return (Number(arr[0]*3.75)/2)+1.25 +'vh'
    },
    userInfo(){
      userInfo().then(res=>{
        if(res.code==0){
          this.getPlanSeat()
        }
      })
    },
    getPlanSeat(){
      let data = {
        cinemaId:this.cinemaId,
        featureAppNo:this.featureAppNo
      }
      getPlanSeat(data).then(res=>{
        //获取座位行编码
        this.endHeight = res.list[res.list.length-1].graphRow
        //区间添加颜色
        res.areas.forEach((item,index)=>{
          if(index==0){
            item.color = '1px solid rgb(180, 223, 247)'
          }else if(index==1){
            item.color = '1px solid rgb(255, 221, 143)'
          }else if(index==2){
            item.color = '1px solid rgb(134, 227, 215)'
          }else if(index==3){
            item.color = '1px solid rgb(253, 161, 151)'
          }else if(index==4){
            item.color = '1px solid rgb(223, 121, 151)'
          }else if(index==5){
            item.color = '1px solid rgb(153, 121, 151)'
          }else if(index==6){
            item.color = '1px solid rgb(103, 121, 151)'
          }else if(index==7){
            item.color = '1px solid rgb(93, 121, 151)'
          }else if(index==8){
            item.color = '1px solid rgb(33, 121, 151)'
          }
        })
        this.areas = res.areas
        // 座位二维数组
        let list = []
        let maxRow = res.list[res.list.length-1].graphRow
        for(let number=0; number<maxRow; number++){
          res.list.forEach((item,index)=>{
            if(item.graphRow==number+1){
              item.isFlase = true
              if(item.seatType=='L'){
                this.isLove = true
              }
              if(this.areas.length>0){
                this.areas.forEach((it,idx)=>{
                  if(it.areaId==item.areaId){
                    item.color = it.color
                    item.price = it.price
                  }
                })
              }else{
                item.price = res.plan.minPrice
                item.color = '1px solid rgb(180, 223, 247)'
              }

              list.push(item)
            }
          })
          this.list[number] = list
          list = []
        }
        console.log(this.list)
        this.plan = res.plan
        this.$forceUpdate()
      }).catch(res=>{
        Dialog.alert({
          message: res.msg,
        }).then(() => {
          this.$router.go(-1)
        });
      })
    },
    bindClick(it,index,idx){
      if(it.seatState==-1) return
      let arrList = this.list[index]
      if(it.isFlase){
        if(this.selectList.length==4){
          Dialog({ message: '最多只能选座四个座位' });
        }else{
          if(it.seatType=='N'){
            this.list[index][idx].isFlase = !this.list[index][idx].isFlase
            this.selectList.push(this.list[index][idx])
          }else if(it.seatType=='R'||it.seatType=='L'){
            if(this.selectList.length<3){
              this.list[index][idx].isFlase = !this.list[index][idx].isFlase
              this.selectList.push(this.list[index][idx])
              this.list[index].forEach((item,idx2)=>{
                if(this.list[index][idx].seatPieceNo==item.seatPieceNo&&this.list[index][idx].seatNo!=item.seatNo){
                  item.isFlase = !item.isFlase
                  this.selectList.push(item)
                }
              })
            }else{
              Dialog({ message: '最多只能选座四个座位' });
            }
          }else if(it.seatType=='M'){

          }

        }
      }else{
        if(it.seatType=='N'){
          this.selectList.forEach((item,index)=>{
            if(item.seatNo==it.seatNo){
              item.isFlase = !item.isFlase
              this.selectList.splice(index,1)
            }
          })
        }else if(it.seatType=='R'||it.seatType=='L'){
          this.selectList.forEach((item,index)=>{
            if(item.seatPieceNo==it.seatPieceNo){
              item.isFlase = !item.isFlase
            }
          })
          let arr = this.selectList.filter(item=>item.seatPieceNo!=it.seatPieceNo)
          this.selectList = arr
        }else if(it.seatType=='M'){

        }
      }
      //获取价格
      let allPrice = 0
      this.selectList.forEach((item,index)=>{
        let a = new Big(allPrice)
        let b = new Big(item.price)
        allPrice = a.plus(b)
      })
      console.log(allPrice)
      this.allPrice = allPrice

      this.$forceUpdate()
    },
    gotoOrder(){
      let time = new Date(this.plan.stime)
      let dqTime = new Date()
      let that = this
      console.log(time.getTime())
      console.log(dqTime.getTime())
      console.log(time.getTime()-dqTime.getTime())
      if(time.getTime()-dqTime.getTime()<1800000){
        Dialog.alert({
          message: '开映时间不足半小时，可能出票失败',
        }).then(() => {
          that.orderOk()
        });
      }else{
        that.orderOk()
      }
    },
    orderOk(){
      let that = this
      //判断是否打开购票通道
      let isOpen = true
      // 判断是否隔开购票
      let newList = JSON.parse(JSON.stringify(this.list))
      console.log(newList)
      let listLength = newList.length
      // 添加是否选中或已出售字符
      for(let i=0; i<listLength; i++){
        newList[i].forEach((item,index)=>{
          if(item.isFlase==false||item.seatState==-1){
            item.isOk = true
          }
        })
      }
      // 判断是否锁座成功
      for(let i=0; i<listLength; i++){
        newList[i].forEach((item,index)=>{
          let endList = newList[i].length-1
          if(item.isFlase == false){
            if(index==0||index==endList){

            }else{
              if(newList[i][index+1].seatState==-1||newList[i][index-1].seatState==-1){

              }else{
                if(index==1){
                  if(newList[i][index-1].isOk){
                  }else{
                    isOpen = false
                  }
                }else if(index==endList-1){
                  if(newList[i][endList].isOk){
                  }else{
                    isOpen = false
                  }
                }else{
                  if(!newList[i][index+1].isOk&&newList[i][index+2].isOk){
                    isOpen = false
                  }
                  if(!newList[i][index-1].isOk&&newList[i][index-2].isOk){
                    isOpen = false
                  }
                }
              }
            }
          }
        })
      }
      if(!isOpen) return this.tipsMessage('请勿隔空选座')
      let seatNo = []
      this.selectList.forEach((item,index)=>{
        seatNo.push(item.seatNo)
      })
      let data = {
        cinemaId:this.cinemaId,
        featureAppNo:this.featureAppNo,
        seatNo:seatNo.toString(',')
      }
      order(data).then(res=>{
        let that = this
        let data = {
          orderId:res.data.id,
          tradeType:'JSAPI',
          openId:getStore('openId')?getStore('openId'):'',
          appId:getStore('appId')?getStore('appId'):''
        }
        prepay(data).then(res=>{
          if (res.msg === 'success') {
            if (typeof WeixinJSBridge === 'undefined') {
              if (document.addEventListener) {
                document.addEventListener('WeixinJSBridgeReady', this.onBridgeReady, false)
              } else if (document.attachEvent) {
                document.attachEvent('WeixinJSBridgeReady', this.onBridgeReady)
                document.attachEvent('onWeixinJSBridgeReady', this.onBridgeReady)
              }
            } else {
              if(window.__wxjs_environment === 'miniprogram'){
                console.log('在小程序')
                wx.miniProgram.postMessage({ data: {base64:res.data} })
                wx.miniProgram.navigateBack({
                  delta: 1, //小程序必须有该目录
                  success() {
                    console.log("跳转成功");
                  },
                  fail(err) {
                    console.log('跳转失败', err)
                  },
                  complete() {
                    console.log("执行");
                  }
                })
              }else{
                that.onBridgeReady(res.data)
              }

            }
          }
        })
      }).catch(res=>{
        Dialog.alert({
          message: res.msg,
        }).then(() => {
        });
      })
    },
    onBridgeReady(data) {
      const that = this
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest',
        {
          appId: data.appId, // 公众号名称，由商户传入
          timeStamp: data.timeStamp, // 时间戳，自1970年以来的秒数
          nonceStr: data.nonceStr, // 随机串
          package: data.packageValue, // 微信订单id
          signType: 'MD5', // 微信签名方式：
          paySign: data.paySign // 微信签名
        },
        function(res) {
          console.log(res)
          if (res.err_msg === 'get_brand_wcpay_request:ok') {
            // 付款成功
            Dialog.alert({
              message: '购买成功',
            }).then(() => {
              that.$router.push({
                path:'/order'
              })
            });
          } else {
            that.tipsMessage('未完成支付...')
          }
        }
      )
    },
    //提示信息
    tipsMessage(text) {
      Dialog.alert({
        message: text,
      }).then(() => {
      });
    },
  },
  watch: {},
};
</script>

<style scoped lang="scss">
  .content{
    min-width: 100vw;
    min-height: 100vh;
    background-color: #fff;
    box-sizing: border-box;
    padding-bottom: 50px;
    overflow: auto;
    .headTop{
      position: fixed;
      top: 0;
      left: 0;
      width: 100vw;
      height: 70px;
      background-color: #fff;
    }
    .statusList{
      overflow: auto;
      height: 50px;
      display: flex;
      margin: 0 auto;
    }
    .topList{
      display: flex;
      align-items: center;
      margin-left: 50px;
      margin-right: 50px;
      flex-shrink: 0;
    }
    .typeIcon{
      width: 15px;
      height: 15px;
      background: url('../../../static/icon13.png') no-repeat;
      background-size: 100% 100%;
    }
    .typeIcon2{
      width: 15px;
      height: 15px;
      margin-left: 10px;
    }
    .lovers{
      width: 30px;
      height: 15px;
      background: url('../../../static/icon11.png') no-repeat;
      background-size: 100% 100%;
      margin-left: 10px;
    }
    .typeName{
      font-size: 11px;
      margin-left: 5px;
      margin-right: 10px;
    }
    .rowContent{
      width: 375px;
      height: 55vh;
      overflow: hidden;
      overflow-y: scroll;
      display: flex;
      box-sizing: border-box;
      padding-left: 10px;
      .leftNumber{
        width: 2.5vh;
        background-color: rgba(146, 146, 146,.4);
        border-radius: 10px;
      }
      .leftList{
        margin-top: 1.25vh;
        line-height: 2.5vh;
        height: 2.5vh;
        text-align: center;
        color: #fff;
      }
    }
    .wSild{
      // height: 1px;
      // background-color: rgba(146, 146, 146,.3);
      position: absolute;
      left: 0;
      border: 1px dotted rgba(146, 146, 146,.5);
      transform: translateY(-50%);
    }
    .hSild{
      border: 1px dotted rgba(146, 146, 146,.5);
      position: absolute;
      top: 0;
      // transform: translateX(-50%);
    }
    .rowList{
      margin-top: 1.25vh;
      display: flex;
      align-items: center;
      flex-shrink: 0;
      height: 2.5vh;
      .colList{
        width: 2.5vh;
        height: 2.5vh;
        background: url('../../../static/icon9.png') no-repeat;
        background-size: 100% 100%;
        flex-shrink: 0;
        box-sizing: border-box;
      }
      .colList2{
        width: 2.5vh;
        height: 2.5vh;
        flex-shrink: 0;
        box-sizing: border-box;
      }
      .colList4{
        width: 5vh;
        height: 2.5vh;
        flex-shrink: 0;
        background: url('../../../static/icon10.png') no-repeat;
        background-size: 100% 100%;
        box-sizing: border-box;
      }
      .colList3{
        width: 5vh;
        height: 2.5vh;
        flex-shrink: 0;
        background: url('../../../static/icon11.png') no-repeat;
        background-size: 100% 100%;
        box-sizing: border-box;
      }
      .colList5{
          width: 2.5vh;
          height: 2.5vh;
          background: url('../../../static/icon13.png') no-repeat;
          background-size: 100% 100%;
          flex-shrink: 0;
          box-sizing: border-box;
      }
      .colList6{
        width: 5vh;
        height: 2.5vh;
        flex-shrink: 0;
        background: url('../../../static/icon14.png') no-repeat;
        background-size: 100% 100%;
        box-sizing: border-box;
      }
    }
  }
  .bottom{
    width: 350px;
    background-color: #fff;
    border-radius: 12.5px;
    position: fixed;
    bottom: 100px;
    left: 12.5px;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.2);
    box-sizing: border-box;
    padding: 7.5px 12.5px;
  }
  .detail{
    width: 100%;
    height: 55px;
    overflow: hidden;
  }
  .detailTitle{
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .name{
    font-size: 14px;
    font-weight: bold;
  }
  .select{
    color: blue;
    font-size: 14px;
  }
  .times{
    font-size: 13px;
    margin-top: 10px;
  }
  .fengexian{
    width: 325px;
    height: 0.5px;
    background-color: rgba(0, 0, 0, .05);
    margin: 7.5px auto 0;
  }
  .addList{
    display: flex;
    align-items: center;
    margin-top: 10px;
  }
  .listDetail{
    background-color: rgb(244, 246, 247);
    width: 80px;
    height: 35px;
    box-sizing: border-box;
    padding: 2.5px 2px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-right: 8px;
  }
  .number{
    font-size: 12px;
  }
  .price{
    font-size: 11px;
    color: red;
  }
  .close{
    width: 10px;
    height: 10px;
    background: url('../../../static/icon12.png') no-repeat;
    background-size: 100% 100%;
  }
  .button{
    width: 350px;
    height: 50px;
    background-color: rgb(231, 161, 156);
    position: fixed;
    bottom: 30px;
    left: 12.5px;
    border-radius: 25px;
    text-align: center;
    line-height: 50px;
    color: #fff;
  }
  .button2{
    width: 350px;
    height: 50px;
    background-color: rgb(219, 76, 65);
    position: fixed;
    bottom: 30px;
    left: 12.5px;
    border-radius: 25px;
    text-align: center;
    line-height: 50px;
    color: #fff;
  }
</style>
